package com.taobao.rigel.rap.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;

import com.leo.common.util.MD5Digest;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import net.sf.json.JSONObject;

/**
 * Created by Bosn on 14-8-25.
 */
public class HTTPUtils {
	private final static org.apache.logging.log4j.Logger logger = LogManager
			.getFormatterLogger(HTTPUtils.class.getName());

	// HTTP GET request
	public static String sendGet(String url) throws Exception {
		if (!url.startsWith("http://")) {
			url = "http://" + url;
		}

		url = url.replaceAll("<", "");
		url = url.replaceAll(">", "");

		String USER_AGENT = "Mozilla/5.0";

		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		// optional default is GET
		con.setRequestMethod("GET");

		// add request header
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Charset", "utf-8");
		con.setRequestProperty("contentType", "utf-8");

		int responseCode = con.getResponseCode();
		logger.info("\nSending 'GET' request to URL : " + url);
		logger.info("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// print result
		// System.out.println(response.toString());
		return response.toString();

	}

	static HttpClient httpclient = new DefaultHttpClient();
	static BasicCookieStore cookieStore = new BasicCookieStore();
	static BasicHttpContext httpContext = new BasicHttpContext();
	static {
		httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
	}

	//处理get 后接参数
	public static Map<String, Object> getParmMap(String url) {
		Map<String, Object> pars = new HashMap<String, Object>();
		if (url.contains("?")) {
			String parms = url.substring(url.indexOf("?") + 1, url.length());
			if (parms.contains("&")) {
				String[] split = parms.split("&");
				for (String s : split) {
					String key = s.substring(0, s.indexOf("="));
					if(key.equals("userId")){
						continue;
					}
					String value = s.substring(s.indexOf("=") + 1, s.length());
					pars.put(key, value);
				}
			} else {
				if (parms.contains("=")) {
					String key = parms.substring(0, parms.indexOf("="));
					String value = parms.substring(parms.indexOf("=") + 1, parms.length());
					if(!key.equals("userId")){
						pars.put(key, value);
					}
				}
			}
		}
		return pars;
	}

	/**
	 * post提交
	 * @since 1.0 
	 * @param url
	 * @return
	 * <br><b>作者： @author Administrator</b>
	 * <br>创建时间：2016年11月11日 下午3:52:11
	 */
	@SuppressWarnings("static-access")
	public static String sendRestInter(String url) {
		

		Map<String, Object> pars = getParmMap(url);
		pars.put("userId", 325713L);
		String smsUrl = url;
		HttpPost httppost = new HttpPost(smsUrl);
		// pars.put("App-Key", "fybao.superjia.com");
		// pars.put("App-Secret", "MT0VT5EN1FAP7SGA840OBW2DUFJUAB");

		httppost.addHeader("App-Key", "iwjw.superjia.com");

		httppost.addHeader("App_Time", new Date().getTime() + "");

		httppost.addHeader("ver", "5.9");
		httppost.addHeader("os", "iphone OS"); // 手机来源 (android / ios)
		httppost.addHeader("imei", "864394104014198");

		// httppost.addHeader("os", "android"); //手机来源 (android / ios)
		// httppost.addHeader("imei", "865790021171558");
		// httppost.addHeader("model", "MiNote");

		String strResult = "";

		try {

			// List<NameValuePair> nameValuePairs = new
			// ArrayList<NameValuePair>();
			JSONObject jobj = new JSONObject();
			if (pars != null) {
				Iterator<String> iter = pars.keySet().iterator();
				while (iter.hasNext()) {
					String key = iter.next();
					Object value = pars.get(key);
					jobj.put(key, value);
					if ("userId".equals(key)) {
						long userId = (Long) value;
						httppost.addHeader("uticket", AuthUtil.getLoginTicket(userId));
					}
				}
			}

			List<Map.Entry<String, Object>> params = new ArrayList<Map.Entry<String, Object>>(pars.entrySet());//
			Collections.sort(params, new Comparator<Map.Entry<String, Object>>() {
				public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
					if (o1.getKey() == null || o2.getKey() == null)
						return 0;
					return o1.getKey().compareTo(o2.getKey());
				}
			});

			// a=1&b=b&MT0VT5EN1FAP7SGA840OBW2DUFJUAB&1100000000
			String secret = "";
			for (Map.Entry<String, Object> param : params) {
				String key = param.getKey();
				String value = "";
				Object value1 = param.getValue();
				if (value1.getClass().isArray()) {
					String[] ta = (String[]) param.getValue();
					if (ta != null && ta.length > 0) {
						for (int i = 0; i < ta.length; i++) {
							if (i == 0) {
								value = "[" + ta[0];
							} else {
								value = value + ", " + ta[i];
							}

							if (i == (ta.length - 1)) {
								value += "]";
							}
						}
					}
				} else {
					value = value1.toString();
				}
				secret = secret + key + "=" + value + "&";
			}
			System.out.println(secret);
			if (secret.endsWith("&"))
				secret = secret.substring(0, secret.length() - 1);

			long currentTime = System.currentTimeMillis() / 1000000;
			// KX3RFJ6YB6FNR1DQAHGLYPWSEW0OQF
			String secret_ = secret + "&" + "KX3RFJ6YB6FNR1DQAHGLYPWSEW0OQF" + "&" + currentTime;
			// logger.info(secretFirst);
			String md5 = MD5Digest.getMD5Digest(secret_);
			System.out.println(secret_);
			System.out.println(md5);
			httppost.addHeader("App-Secret", md5);

			// nameValuePairs.add(new BasicNameValuePair("msg",
			// getStringFromJson(jobj)));
			// httppost.addHeader("Content-type",
			// "application/x-www-form-urlencoded");
			// httppost.setEntity(new
			// UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			BasicHttpEntity en = new BasicHttpEntity();
			en.setContentType("application/json");
			String str = jobj.toString();
			if (str == null) {
				str = "";
			}
			byte[] bytes = str.getBytes();

			ByteInputStream bis = new ByteInputStream(bytes, bytes.length);
			en.setContent(bis);
			httppost.setEntity(en);

			JSONObject sobj = null;
			HttpResponse response = httpclient.execute(httppost, httpContext);
			if (response.getStatusLine().getStatusCode() == 200) {
				sobj = new JSONObject();
				/* 读返回数据 */
				String conResult = EntityUtils.toString(response.getEntity());
				System.out.println("------------------" + conResult);
				sobj = sobj.fromObject(conResult);
				strResult = sobj.toString();
			} else {
				String err = response.getStatusLine().getStatusCode() + "";
				strResult += "发送失败:" + err;
			}
			return sobj == null ? "" : sobj.toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
